package com.krui.iweibo.ui;

import java.util.HashMap;
import java.util.Map;

import weibo4android.User;
import weibo4android.http.AccessToken;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.krui.iweibo.R;
import com.krui.iweibo.model.Task;
import com.krui.iweibo.model.UserInfo;
import com.krui.iweibo.service.MainService;
import com.krui.iweibo.utils.OAuthUtils;
import com.krui.iweibo.utils.SharedPreferenceUtil;

public class AuthActivity extends BaseActivity implements IweiboActivity
{

	private static final String  TAG = "AuthActivity";
	
	/** 自定义dialog*/
	private Dialog dialog;
	
	private static final int RESPONSE_URL = 5;
	
	private ProgressDialog pDialog;
	
	private static final int GET_ACCESS_TOKEN_DLG = 1;
	
	private static final int GET_AUTHORIZATIONURL_DLG = GET_ACCESS_TOKEN_DLG + 1;
	
	private static final int GET_USER_ICON_DLG = GET_AUTHORIZATIONURL_DLG + 1;
	
	
	
	//private String authorizationURL;
	
	
	protected void onCreate(Bundle savedInstanceState)
	{
		
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.auth);
		
		
		View digView = View.inflate(this, R.layout.authorize_dialog, null);
		
		dialog = new  Dialog(this, R.style.auth_dialog);
		dialog.setContentView(digView);
		dialog.show();
		
		
		Button btnBegin=(Button) digView.findViewById(R.id.btn_auth_begin);
		
		
		btnBegin.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				Task task = new Task(Task.GET_AUTHORIZATIONURL, null);
				MainService.newTask(task);
				MainService.addActivity(AuthActivity.this);
				showDialog(GET_AUTHORIZATIONURL_DLG);
				dialog.dismiss();
			}
		});
		
	}
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		
		
		super.onResume();
	}
	
	
	
	@Override
	protected void onStop() {
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		
		super.onDestroy();
	}


	@Override
	public void init() {
		
	}


	@Override
	public void refresh(Object... params) {
		if (params[0] instanceof AccessToken) {
			
			dismissDialog(GET_ACCESS_TOKEN_DLG);
			
			AccessToken accessToken = (AccessToken)params[0];
			
			//Log.i("TAG", "get token -- > " + accessToken);
			UserInfo user = null;
			
			//将token信息保存在数据库中
			if (dbAccess.getUserById(null,accessToken.getUserId() + "") == null) {
				user = new UserInfo(accessToken.getUserId() + "", accessToken.getScreenName(),accessToken.getToken()
						, accessToken.getTokenSecret(), "1");
				dbAccess.savaUserInfo(user);
				Log.d(TAG, "save user to db. userScreenName = " + accessToken.getScreenName());
			}else {//更新用户token
				dbAccess.updateUserInfo(user);
				Log.d(TAG, "update user...");
			}
			
			//根据获得的token得到头像信息
			Map<String, Object> taskParams = new HashMap<String, Object>(1);
			taskParams.put("user",user );
			Task task = new Task(Task.GET_USER_ICON, taskParams);
			MainService.newTask(task);
			MainService.addActivity(AuthActivity.this);
			showDialog(GET_USER_ICON_DLG);
			
			
		}else if(params[0] instanceof String){
			
			dismissDialog(GET_AUTHORIZATIONURL_DLG);
			//在webview页面进行授权，返回pin值到本页面
		//	intent2What(AuthActivity.this, WebViewActivity.class, false);
			Intent intent = new Intent(AuthActivity.this, WebViewActivity.class);
			intent.putExtra("url", (String)params[0]);
			startActivityForResult(intent,RESPONSE_URL);
			
		}else if(params[0] instanceof UserInfo){//获取用户头像
			
			dismissDialog(GET_USER_ICON_DLG);
			UserInfo userInfo = (UserInfo)params[0];
			dbAccess.updateUserInfo(userInfo.getUserId(), userInfo.getUserName(), userInfo.getUserIcon());
			
			String loginTime = System.currentTimeMillis() + "";
			
			//记录登录时间
			dbAccess.updateUserLoginTime(userInfo.getUserId(), loginTime);
			
			SharedPreferenceUtil.savaLoginUser(this, userInfo);
			
			intent2Where(AuthActivity.this, LoginActivity.class, true);

		}
		
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		
		case RESPONSE_URL:
			if (data != null) {
				
				String pin = data.getStringExtra("pin");
				
				System.out.println(pin);
				
				//这里获取accessToken是一个耗时操作，放在service线程中异步执行
				
				Task task = new Task(Task.GET_ACCESS_TOKEN, null);
				MainService.newTask(task);
				MainService.addActivity(AuthActivity.this);
				showDialog(GET_ACCESS_TOKEN_DLG);
				
			}
			break;

		default:
			break;
		}
		
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch (id) {
		case GET_ACCESS_TOKEN_DLG:
			
			if (pDialog != null) {
				pDialog.setMessage(getString(R.string.get_access_token_ing));
			}
			break;
			
		case GET_AUTHORIZATIONURL_DLG:
			if (pDialog == null) {
				pDialog = new ProgressDialog(this);
				pDialog.setMessage(getString(R.string.get_authroizationurl));
			}
			
			break;
			
		case GET_USER_ICON_DLG:
			if (pDialog != null) {
				pDialog.setMessage(getString(R.string.get_user_icon));
			}

			break;
		default:
			break;
		}
		
		
		return pDialog;
	}
	
	
	
}
